'use client';
import React, { useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import message from '@/components/common/message';
import { ROUTE_DASHBOARD, LOCAL_USER, SESSION_INFORMATION, SESSION_USERS } from '@/config/settings';
import From from '@/components/admin/auth/Form';

export default function Login() {
  const router = useRouter();
  const formRef = useRef(null);

  const onFinish = async (e) => {
    e.preventDefault();
    const form = formRef.current;
    const values = { username: form.username.value, password: form.password.value, };
    try {
      let data = await fetch('/api/admin/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify(values) });
      data = await data.json();
      if (data.code === 0) {
        message.success(data.codeMap[data.code]);
        localStorage.setItem(LOCAL_USER, JSON.stringify(data.userInfo));
        router.push(ROUTE_DASHBOARD);
      } else {
        message.error(data.codeMap[data.code]);
      }
    } catch (err) {
      message.error("网络错误");
    }
  };

  useEffect(() => {
    Promise.all([
      fetch('/api/admin/auth/me', { method: 'GET', credentials: 'include' }).then(res => res.json()),
      fetch('/api/contact', { method: 'GET', credentials: 'include' }).then(res => res.json()),
      fetch('/api/admin/users', { method: 'GET', credentials: 'include' }).then(res => res.json())
    ]).then(([authData, infoData, usersData]) => {
      if (authData.code === 0) {
        localStorage.setItem(LOCAL_USER, JSON.stringify(authData.userInfo));
        router.push(ROUTE_DASHBOARD);
      }
      if (infoData.code === 0) { sessionStorage.setItem(SESSION_INFORMATION, JSON.stringify(infoData.data)); }
      if (usersData.code === 0) { sessionStorage.setItem(SESSION_USERS, JSON.stringify(usersData.data)); }
    });
  }, [router]);

  return (
    <section className="w-full h-screen overflow-hidden grid place-items-center bg-[var(--bg-color)] bg-cover bg-center bg-no-repeat">
      <From accountName={'登录账号'} passwordName={'登录密码'} buttonName={'登录'} formRef={formRef} onFinish={onFinish} linkName={'去注册账号'} linkHref={'/admin/auth/register'} />
    </section>
  );
}